import { useParams } from 'react-router-dom'
import { useRequest } from 'ahooks'
import { getQuestionService } from '../../../services/question'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { componentAction } from '../../../store/components-reducer'
import { pageInfoAction } from '../../../store/page-info-reducer'

export default function useLoadQuestionData() {
  const { id = '' } = useParams()
  const dispatch = useDispatch()

  const { data, error, loading, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error('没有问卷 id')
      return await getQuestionService(id)
    },
    { manual: true }
  )

  useEffect(() => {
    run(id)
  }, [id])

  useEffect(() => {
    if (!data) return
    const { componentList = [], title, desc, js, css } = data

    let selectedId = ''
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id!
    }

    dispatch(componentAction.resetComponents({ componentList, selectedId, copiedComponent: null }))

    dispatch(pageInfoAction.resetPageInfo({ title, desc, js, css }))
  }, [data])

  return { error, loading }
}
